package com.itheima.img;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import java.util.UUID;

import com.itheima.common.JsonResult;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * @author ChenJunJie
 * @date 2022/6/15 9:16
 * 图片上传的service层
 */
@Service
public class ImagesService {

    //文件上传
    public JsonResult<String> uploadfile(MultipartFile multipartFile, String username) {

        //外网访问的Endpoint（地域节点）
        String endpoint = "oss-cn-hangzhou.aliyuncs.com";
        // 阿里云账号AccessKey
        String accessKeyId = "LTAI5tHNZ7C2S1vjid1CGknF";
        String accessKeySecret = "xbhWXqNCg71PjDUPOYxTwL0QORVOl4";
        // Bucket名称
        String bucketName = "reggiee-img";

        OSS ossClient = null;
        try {
            // 创建OSSClient实例。
            ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);

            // 2: 获取文件上传的流
            InputStream inputStream = multipartFile.getInputStream();
            // 3：构建日期目录
            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd");
            String datePath = dateFormat.format(new Date());

            // 4: 获取文件名

            //获取源文件名
            String originname = multipartFile.getOriginalFilename();
            //创建uuid
            String filename = UUID.randomUUID().toString();
            //获取源文件的后缀名
            String suffix=null;
            if (originname!=null){
                suffix = originname.substring(originname.lastIndexOf("."));
            }

            String newName = filename + suffix;
            //拼接链接名
            String fileUrl = username+"/"+datePath + "/" + newName;
            //5：文件上传到阿里云服务器
            ossClient.putObject(bucketName, fileUrl, inputStream);

            String url = "https://" + bucketName + "." + endpoint + "/" + fileUrl;

            return JsonResult.imgSuccess(url, "上传成功");
        } catch (Exception e) {
            e.printStackTrace();
            return JsonResult.error("上传失败");
        } finally {
            if (ossClient!=null){
                ossClient.shutdown();
            }
        }

    }

}
